//
//  STBaseViewController.swift
//  RouterPushProtocol
//
//  Created by Toj on 2/21/22.
//

import UIKit
import TTCOM_iOS

open class STBaseViewController: UIViewController {
    private var _prefersStatusBarHidden = false
    var st_prefersStatusBarHidden: Bool {
        get {
            return _prefersStatusBarHidden
        }
        set {
            _prefersStatusBarHidden = newValue
        }
    }
    
//    open override var prefersStatusBarHidden: Bool {
//        print("-->startimes: func:\(#function)")
//        return _prefersStatusBarHidden
//    }
    
    open override var shouldAutorotate: Bool {
        return true
    }
    
    // 支持哪些屏幕方向
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
    
    public var ads: [String: [FloatADModel]]? {
        didSet {
            setupPitADs()
        }
    }
    
    private func setupPitADs() {
        var views = [STCirculationView]()
        guard let _ads = ads else {
            FloatADManager.manager.setCuttrentViews(views)
            return
        }
        
        let navBarIsHidden = navigationController?.navigationBar.isHidden ?? true
        
        for (_, value) in _ads {
            let v = STCirculationView()
            views.append(v)
            v.delegage = self
            v.isDragging = false
            v.datas = value
            view.addSubview(v)
            
            let ad = value.first
            let placement = ad?.player_placement ?? .left
            let type = ad?.ad_type_code ?? .icon
            var bottom = ad?.from_the_bottom ?? 0
            var width: CGFloat = 70
            var height: CGFloat = 95
            
            var x: CGFloat = 20
            if placement == .right {
                x = CGFloat.sr_width - width - 20
            }
            
            if type == .banner {
                bottom = 0
                width = 250
                x = (CGFloat.sr_width - width) * 0.5
                height = 80
            }
            
            let showHeight = (CGFloat.sr_height - CGFloat.nav_barFullHeight - CGFloat.tab_barFullHeight - height)
            var y = showHeight * (1 - (CGFloat(bottom) / 100.0))
            if navBarIsHidden { y += CGFloat.nav_barFullHeight }
            
            let frame = CGRect(x: x, y: y, width: width, height: height)
            height -= 25
            v.circulationSize = CGSize(width: width, height: height)
            v.frame = frame
        }
        
        FloatADManager.manager.setCuttrentViews(views)
    }
    
    public var tt_isNavigationBarHidden = false {
        didSet {
            navigationBar.isHidden = !tt_isNavigationBarHidden
        }
    }
    private(set) lazy var navigationBar: STNavigationBar = {
        let view = STNavigationBar()
        view.isHidden = true
        return view
    }()
    
    private var isFront = false
    
    open override var title: String? {
        set {
            super.title = newValue
            navigationBar.title = newValue ?? ""
        }
        get { return super.title }
    }
    
    private(set) var statusBarView: UIView?
    
    open override func loadView() {
        super.loadView()
        // print("-->toj: className:" + cm_className + " func: " + #function)
    }
    
    private(set) var adUID = ""
    
    open override var view: UIView! {
        set {
            super.view = newValue
            CM.begin(time: st_objectName)
        }
        get { return super.view }
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        let adUnitIDCount = UInt32(adUnitIDs.count)
        let adUnitIDIndex = Int(arc4random_uniform(adUnitIDCount))
        // print("-->toj: ad UnitID Index: \(adUnitIDIndex)")
        adUID = adUnitIDs[adUnitIDIndex]
        
        view.backgroundColor = .random
        // print("-->toj: className:" + cm_className + " func: " + #function)
        extendedLayoutIncludesOpaqueBars = true
        
        view.addSubview(navigationBar)
        if let _ = navigationController {
            let statusBarBackgroundView = UIView()
            statusBarView = statusBarBackgroundView
            statusBarBackgroundView.backgroundColor = .navigation
            view.addSubview(statusBarBackgroundView)
            statusBarBackgroundView.snp.makeConstraints { make in
                make.top.left.right.equalTo(view)
                make.height.equalTo(CGFloat.nav_barFullHeight)
            }
        }
        
//        STInterstitialAdManager.manager.delegate = self
//        STInterstitialAdManager.manager.loadInterstitialAd(unitID: adUID)
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        defer {
            if !isFront {
                isFront = true
                view.bringSubviewToFront(navigationBar)
            }
        }
        
       // print("-->toj: className:" + cm_className + " func: " + #function)
        
        navigationController?.setNavigationBarHidden(tt_isNavigationBarHidden, animated: animated)
        
        // let path = pagePath
        // FloatADManager.manager.fetchVCADs(page: path) { ads in
        // self.ads = ads
        // }
    }
    
    open override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        // print("-->toj: className:" + cm_className + " func: " + #function)
        
        navigationBar.snp.remakeConstraints { make in
            make.left.top.right.equalTo(view)
            make.height.equalTo(CGFloat.nav_barFullHeight)
        }
        
        statusBarView?.snp.remakeConstraints { make in
            make.top.left.right.equalTo(view)
            make.height.equalTo(CGFloat.nav_barFullHeight)
        }
    }
    
    open override func viewDidLayoutSubviews() {
        super.viewWillLayoutSubviews()
        // print("-->toj: className:" + cm_className + " func: " + #function)
    }
    
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // print("-->toj: className:" + cm_className + " func: " + #function)
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        _ = CM.end(time: st_objectName)
    }
    
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // print("-->toj: className:" + cm_className + " func: " + #function)
        
        // FloatADManager.manager.cuttrentCirculationViews.forEach { view in
        //   view.stopTimer()
        //   view.removeFromSuperview()
        // }
        // FloatADManager.manager.cuttrentCirculationViews.removeAll()
    }
    
    open override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        // print("-->toj: className:" + cm_className + "func: " + #function)
    }
    
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        // print("-->toj: \(arc4random_uniform(111111))")
        
        // navigationController?.pushViewController(STBaseViewController(), animated: true)
        
        // let delegate = UIApplication.shared.delegate as? AppDelegate
        // let tbc = delegate?.window?.rootViewController as? STTabBarController
        // tbc?.isMatch = arc4random_uniform(2) == 1
    }
    
    deinit {
        print("-->toj: class: " + cm_className, "func: deinit")
    }
}

extension STBaseViewController: STCirculationViewDelegate {
    func circulationViewDidTapClose(view: STCirculationView) {
        let ads = view.datas
        ads?.forEach({ $0.isClosed = true })
        view.removeFromSuperview()
    }
    
    func circulationView(view: STCirculationView, didSelectedModel: FloatADModel) {
        navigationController?.pushViewController(QrViewController(), animated: true)
    }
}
